<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class moneylog extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'songshu:mongylog';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '监听用户资金日志，分布到100张表中';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        while(true) {
            $list = DB::table('ref_handle')->where('ref_status',0)->orderBy('id','desc')->limit(10)->get()->toArray();
            if(empty($list)) {
                sleep(1);
            }else {
                foreach($list as $item) {
                    $json = json_decode($item->ref_data, true);
                    $data = $json['data'];
                    $uid = $data['uid'];
                    $suffix = substr($uid, -2);
                    if($suffix<10) {
                        $suffix = str_pad($suffix, 2, "0", STR_PAD_LEFT);
                    }
                    $table = 'refererdata_'.$suffix;
                    DB::beginTransaction();
                    $insert = DB::connection('db3')->table($table)->insert([
                        'uid'=>$uid,
                        'ref_u_id'=>$data['ref_u_id'],
                        'ref_m_id'=>$data['ref_m_id'],
                        'td_id'=>$data['td_id'],
                        'ts_id'=>$data['ts_id'],
                        'income_type'=>$data['income_type'],
                        'task_id'=>$data['task_id'],
                        'coin'=>$data['coin'],
                        'rate'=>$data['rate'],
                        'money'=>$data['money'],
                        'use_gifts_id'=>$data['use_gifts_id'],
                        'added_coin'=>$data['added_coin'],
                        'identifying'=>$data['identifying'],
                        'type'=>$data['type'],
                        'time'=>$data['time'],
                        'ymd'=>$data['ymd'],
                    ]);
                    $update = DB::table('ref_handle')->where('id', $item->id)->update(['ref_status'=>1]);
                    if($insert!==false && $update)
                    {
                        DB::commit();
                        echo $table."\n";
                    }else {
                        DB::rollBack();
                        echo "rollBack"."\n";
                    }
                }
            }
        }
    }
}
